package com.vicente.managerdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vicente.managerdemo.common.ResultBean;
import com.vicente.managerdemo.dto.UserQueryDto;
import com.vicente.managerdemo.entity.User;
import com.vicente.managerdemo.mapper.UserMapper;
import com.vicente.managerdemo.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 爬虫作业监控接收人表 服务实现类
 * </p>
 *
 * @author vicente
 * @since 2024-12-03
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public ResultBean queryPage(UserQueryDto queryDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(queryDto.getName())){
            queryWrapper.like("username", queryDto.getName());
        }
        if (StringUtils.isNotEmpty(queryDto.getEmail())){
            queryWrapper.like("email_addr", queryDto.getEmail());
        }
        Page<User> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        return ResultBean.getSuccess(userPage);
    }

    @Override
    public ResultBean insertUser(User user) {
        QueryWrapper<User> queryEmail = new QueryWrapper<User>().eq("email_addr", user.getEmailAddr());
        if (!userMapper.selectList(queryEmail).isEmpty()) {
            return ResultBean.getFail("存在同名邮箱,新增失败");
        }
        QueryWrapper<User> queryUserId = new QueryWrapper<User>().eq("user_id", user.getUserId());
        if (!userMapper.selectList(queryUserId).isEmpty()) {
            return ResultBean.getFail("该用户ID已存在");
        }
        int insert = userMapper.insert(user);
        if (insert > 0) {
            return ResultBean.getSuccess("新增成功");
        }
        return ResultBean.getFail("新增失败");

    }

    @Override
    public ResultBean updateUser(User user) {
        int update = userMapper.updateById(user);
        if (update > 0) {
            return ResultBean.getSuccess("更新成功");
        }
        return ResultBean.getFail("更新失败");
    }

    @Override
    public ResultBean deleteById(int id) {
        int delete = userMapper.deleteById(id);
        if (delete > 0) {
            return ResultBean.getSuccess("删除成功");
        }
        return ResultBean.getFail("删除失败");
    }

    @Override
    public ResultBean getAllUsers() {
        return ResultBean.getSuccess(userMapper.selectList(new QueryWrapper<>()));
    }
}
